package sort.leetcode;

/**
 * 148. 排序链表
 * @author haomin
 * @date 2022/03/23 18:41
 **/
public class Num148_sortList {
    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    //方法一
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        //new 了一个数组存储链表中元素
        int size = 1;
        for(ListNode x = head;x.next !=null;x = x.next){
            size ++ ;
        }
        int[] arr = new int[size];
        ListNode x = head;
        for (int i = 0; i < arr.length; i++) {
            arr[i] =x.val;
            x = x.next;
        }


        //数组元素排序-选择排序
        for (int j = 0; j < arr.length; j++) {
            int min = j;
            for (int k = j + 1; k < arr.length; k++) {
                if(arr[min] > arr[k]){
                    min = k;
                }
            }
            int temp = arr[j];
            arr[j] = arr[min];
            arr[min] = temp;
        }

        //将数组中元素导入链表
        ListNode y = head;
        for (int i = 0; i < arr.length; i++) {
            y.val = arr[i];
            y = y.next;
        }
        return head;
    }

    //方法二(归并方法)
    public ListNode sortList2(ListNode head) {
        return head == null ? null : mergeSort(head);
    }

    private ListNode mergeSort(ListNode head) {
        if (head.next == null) {
            return head;
        }

        //一个走一步，另一个走两步，当后一个走到末尾，前一个为链表近似中间位置
        ListNode p = head, q = head, pre = null;
        while (q != null && q.next != null) {
            pre = p;
            p = p.next;
            q = q.next.next;
        }
        pre.next = null;

        ListNode l = mergeSort(head);
        ListNode r = mergeSort(p);
        return merge(l, r);
    }

    //归并
    ListNode merge(ListNode l, ListNode r) {
        //新建一个链表
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;

        //当l,r链都不为空时
        while (l != null && r != null) {
            if (l.val <= r.val) {
                cur.next = l;
                cur = cur.next;
                l = l.next;
            } else {
                cur.next = r;
                cur = cur.next;
                r = r.next;
            }
        }
        //r链已为空，直接插入l链
        if (l != null) {
            cur.next = l;
        }
        //l链已为空，直接插入r链
        if (r != null) {
            cur.next = r;
        }
        return dummyHead.next;
    }
}
